import { ref, inject, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
export default function () {
  let socket: any = inject('socket')
  let route = useRoute()
  const store = useStore()
  let { userName, id } = route.query

  if (navigator.mediaDevices.getUserMedia) {
    console.log('ok')
  } else {
    alert('浏览器不支持 getUserMedia')
    //   console.error('浏览器不支持 getUserMedia')
  }

  let size = ref([
    {
      visibility: 'hidden',
    },
    {
      visibility: 'hidden',
    },
    {
      visibility: 'hidden',
    },
    {
      visibility: 'hidden',
    },
  ])
  let timer: any = null
  let isTalk = ref(false)
  let cancelSend = ref(false)
  let y = 0
  let moveUp = 0

  var chunks: BlobPart[] = []
  //   var blob = null
  let mediaRecorder: MediaRecorder | null = null

  function setSize(index: number) {
    size.value.forEach(item => {
      item.visibility = 'hidden'
    })
    for (let i = 0; i < index; i++) {
      size.value[size.value.length - 1 - i].visibility = 'visible'
    }
  }

  function startTalk(e) {
    y = e.changedTouches[0].clientY
    moveUp = 0
    cancelSend.value = false
    startRec()
    isTalk.value = true
    timer && clearInterval(timer)
    timer = setInterval(() => {
      let index = Math.floor(Math.random() * 4 + 1)
      setSize(index)
    }, 350)
  }

  function endTalk() {
    isTalk.value = false
    timer && clearInterval(timer)
    mediaRecorder && mediaRecorder.stop()
  }

  function touchmove(e: { changedTouches: { clientY: number }[] }) {
    moveUp = y - e.changedTouches[0].clientY
    if (moveUp > 210) {
      if (cancelSend.value) return
      cancelSend.value = true
    } else {
      if (!cancelSend.value) return
      cancelSend.value = false
    }
  }

  function startRec() {
    const constraints = { audio: true }
    navigator.mediaDevices.getUserMedia(constraints).then(
      stream => {
        console.log('授权成功！')
        mediaRecorder = new MediaRecorder(stream)
        mediaRecorder.start()
        // if (mediaRecorder.state === 'recording') {
        //   mediaRecorder.stop()
        //   console.log('录音结束')
        // } else {
        //   mediaRecorder.start()
        //   console.log('录音中...')
        // }

        console.log('录音器状态：', mediaRecorder.state)

        mediaRecorder.ondataavailable = e => {
          chunks.push(e.data)
        }

        mediaRecorder.onstop = e => {
          const blob = new Blob(chunks, { type: 'audio/ogg; codecs=opus' })

          if (cancelSend.value) {
            console.log('取消发送')
          } else {
            console.log('发送成功')
            socket.socket.emit('exchange', {
              to: userName,
              msg: {
                type: 'rec',
                blob,
              },
            })
            store.commit('setMsg', {
              from: userName,
              msg: {
                type: 'rec',
                blob,
              },
              isSelf: true,
            })
          }
          chunks = []
        }
      },
      () => {
        console.error('授权失败！')
      }
    )
  }

  return {
    size,
    isTalk,
    cancelSend,
    startTalk,
    endTalk,
    touchmove,
  }
}
